package com.android.scanner.fragment;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.android.scanner.R;
import com.android.scanner.adapter.CommonAdapter;
import com.android.scanner.adapter.SelectAdapter;
import com.android.scanner.bean.ProjectBean;
import com.android.scanner.utils.Constant;
import com.android.scanner.utils.LoadingUtil;
import com.android.scanner.utils.PreferencesUtil;
import com.android.scanner.utils.SoapUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DeleteFragment extends BaseFragment implements OnClickListener,
		OnItemSelectedListener, OnItemClickListener {
	private Handler handler;
	private Context context;
	private List<String> list = null;
	private List<ProjectBean> lb = null;
	private SelectAdapter adapter = null;
	private ListView lv;
	private TextView tvPara;
	private Button btnLeft, btnMiddle, btnRight;
	private int curPosition = 0;
	private Gson gson = null;
	private int count = 0, checkedCount = 0;
	private static DeleteFragment mSelft = null;

	public static DeleteFragment getInstance(Handler handler) {
		if (mSelft != null)
			return mSelft;
		return new DeleteFragment(handler);
	}

	public DeleteFragment(Handler handler) {
		this.handler = handler;
	}

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			count++;
			if (count == checkedCount) {
				LoadingUtil.hide();
				String str = String.format(
						context.getResources().getString(R.string.deletecount),
						count);
				Toast.makeText(context, str, Toast.LENGTH_SHORT).show();

				for (int i = 0; i < lb.size(); i++) {
					if (lv.isItemChecked(i)) {
						lb.remove(i);
						list.remove(i);

					}
				}
				curPosition = 0;
				adapter.updateHLPosition(curPosition);

				String json = gson.toJson(lb);
				PreferencesUtil.setStringPref(context,
						PreferencesUtil.NAME_WORKLIST, json);
				
				String str1 = String.format(
						context.getResources().getString(R.string.arg_value),
						list.size());
				tvPara.setText(str1);
			}
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		context = getActivity();
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_delete, null);
		gson = new Gson();

		initViews(view);
		return view;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		// if (adapter != null) {
		// Log.e("kirk", "kirk add - curPosition is " + curPosition);
		// lv.setSelection(curPosition);
		// adapter.updateHLPosition(curPosition);
		// }
		super.onResume();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	private void initViews(View view) {
		// TODO Auto-generated method stub

		tvPara = (TextView) view.findViewById(R.id.tv_para);
		btnLeft = (Button) view.findViewById(R.id.btn_left);
		btnMiddle = (Button) view.findViewById(R.id.btn_middle);
		btnRight = (Button) view.findViewById(R.id.btn_right);
		btnLeft.setOnClickListener(this);
		btnMiddle.setOnClickListener(this);
		btnRight.setOnClickListener(this);

		String json = PreferencesUtil.getStringPref(context,
				PreferencesUtil.NAME_WORKLIST, "");

		if (!json.equals("")) {
			Type typeToken = new TypeToken<List<ProjectBean>>() {
			}.getType();
			lb = gson.fromJson(json, typeToken);
		}

		list = new ArrayList<String>();

		for (int i = 1; i < lb.size(); i++)
			list.add(lb.get(i).Name);
		
		String str = String.format(
				context.getResources().getString(R.string.arg_value),
				list.size());
		tvPara.setText(str);
		
		lv = (ListView) view.findViewById(R.id.lv);

		adapter = new SelectAdapter(context, list, lv, curPosition);
		lv.setAdapter(adapter);
		lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		lv.requestFocus();
		lv.setSelection(curPosition);

		lv.setOnItemSelectedListener(this);
		lv.setOnItemClickListener(this);
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if (arg0.getId() == R.id.btn_left) {
			LoadingUtil.show(context, R.string.deleting);
			deleteWorks();
		} else if (arg0.getId() == R.id.btn_middle) {
			if (lv.getCheckedItemCount() < list.size()) {
				for (int i = 0; i < list.size(); i++) {
					lv.setItemChecked(i, true);
				}
				btnMiddle.setText(R.string.unselectall);
			} else {
				for (int i = 0; i < list.size(); i++) {
					lv.setItemChecked(i, false);
				}
				btnMiddle.setText(R.string.selectall);
			}
		} else if (arg0.getId() == R.id.btn_right) {
			handler.sendEmptyMessage(Constant.MSG_BACK_OPTION);
		}
	}

	private void deleteWorks() {
		// TODO Auto-generated method stub
		count = 0;
		checkedCount = 0;
		for (int i = 0; i < lb.size(); i++) {
			if (lv.isItemChecked(i)) {
				checkedCount++;
				Log.i("kirk", "kirk add - i is " + i);
				Map map = new LinkedHashMap<String, String>();
				map.put("method", SoapUtil.METHOD_DELETEPROJECTS);
				map.put("action", SoapUtil.ACTION_DELETEPROJECTS);
				map.put("projectId", lb.get(i).ProjectID);

				SoapUtil.runMethod(map, mHandler);
			}
		}

	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		// TODO Auto-generated method stub
		curPosition = arg2;
		adapter.updateHLPosition(curPosition);
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public boolean setKeyEvent(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		// Toast.makeText(context, "key Event is " + keyCode,
		// Toast.LENGTH_SHORT)
		// .show();
		// if (keyCode == KeyEvent.KEYCODE_D) {
		// if (curPosition < list.size() - 1)
		// lv.setSelection(curPosition + 1);
		//
		// } else if (keyCode == KeyEvent.KEYCODE_U) {
		// if (curPosition > 0)
		// lv.setSelection(curPosition - 1);
		//
		// } else
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			btnLeft.callOnClick();
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			btnRight.callOnClick();
		} else if (keyCode == KeyEvent.KEYCODE_F5) {
			btnMiddle.callOnClick();
		} else if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {

			// lv.setItemChecked(curPosition, !lv.isItemChecked(curPosition));
			// adapter.updateHLPosition(curPosition);
		}
		return super.setKeyEvent(keyCode, event);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		Log.i("kirk",
				"kirk add - Delete click is " + arg2 + ", "
						+ lv.isItemChecked(arg2));
		// lv.setItemChecked(arg2, !lv.isItemChecked(arg2));
		adapter.updateHLPosition(arg2);
	}

}
